from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types,Goods,Order,Users
from django.db.models import Q

# Create your views here.

# 订单列表
def orderlist(request):

	# 获取订单所有的数据
	# objs = Order.objects.all()

	# 搜索
	types = request.GET.get('types',None)
	keywords = request.GET.get('keywords','')
	# 新建空集合
	objs = Order.objects.none()
	if types:
		if types == 'all':
			from django.db.models import Q
			objs = Order.objects.filter(Q(id__contains=keywords)|Q(addtime__contains=keywords)|Q(totalprice__contains=keywords)|Q(totalnum__contains=keywords))
		elif types == 'id':
			objs = Order.objects.filter(id__contains=keywords)

		elif types == 'addtime':
			objs = Order.objects.filter(addtime__contains=keywords)

		elif types == 'user':
			objuser = Users.objects.filter(username__contains=keywords)
			for v in objuser:
				objs = objs | v.order_set.all()

		elif types == 'totalprice':
			objs = Order.objects.filter(totalprice__contains=keywords)

		elif types == 'totalnum':
			objs = Order.objects.filter(totalnum__contains=keywords)

		elif types == 'status':

			objs = Order.objects.filter(status__contains=keywords)

	else:
		objs = Order.objects.all()

	data = objs

	# 数据分页
	from django.core.paginator import Paginator
	# 实例化分页类 参数1-参数的数据，参数2-每页显示的数据
	paginator = Paginator(data,5)
	# 当前页码
	p = int(request.GET.get('p',1))
	# 根据当前页码获取当前页码应该显示的数据
	tlist = paginator.page(p)
	# 获取当前页的页码数
	num = paginator.page_range
	
	context = {'data':tlist,'pagenum':num}
	return render(request,'admin/order/list.html',context)


# 更新订单状态
def orderstatus(request):
	oid = request.GET.get('oid')
	status = request.GET.get('status')
	obj = Order.objects.get(id=oid)
	obj.status = int(status)
	obj.save()
	return HttpResponse('orderstatus')

# 订单详情
def orderinfo(request,oid):
	obj = Order.objects.get(id = oid)

	context={'oinfo':obj,}

	a = obj.orderinfo_set.all()
	
	price = 0
	num = 0
	for v in a:
		print(v.price,v.num)
		print(v.gid.pic)
		print(v.gid.title)

	return render(request,'admin/order/info.html',context)

